package com.example.wan_android.http.code

import com.example.wan_android.http.RetrofitClient
import com.example.wan_android.http.bean.UserData

class UserRepository {
    suspend fun fetchLoginUserData(username: String, password: String): Result<UserData> {
        try {
            val response = RetrofitClient.instance.login(username, password)
            if (response.isSuccessful && response.body()?.errorCode == 0) {
                return Result.success(response.body()?.data!!)
            } else {
                return Result.failure(Exception("Error: ${response.body()?.errorMsg}"))
            }
        } catch (e: Exception) {
            return Result.failure(e)
        }
    }

    suspend fun fetchRegisterUserData(
        username: String,
        password: String,
        rePassword: String
    ): Result<UserData> {
        try {
            val response = RetrofitClient.instance.register(username, password, rePassword)
            if (response.isSuccessful && response.body()?.errorCode == 0) {
                return Result.success(response.body()?.data!!)
            } else {
                return Result.failure(Exception("Error: ${response.body()?.errorMsg}"))
            }
        } catch (e: Exception) {
            return Result.failure(e)
        }
    }

    suspend fun fetchExitLogin():Result<UserData>{
        try {
            val response = RetrofitClient.instance.logout()
            if (response.isSuccessful && response.body()?.errorCode == 0) {
                return Result.success(response.body()?.data!!)
            } else {
                return Result.failure(Exception("Error: ${response.body()?.errorMsg}"))
            }
        } catch (e: Exception) {
            return Result.failure(e)
        }
    }
}